// tvgids spulletjes
#include <curl/curl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <ctype.h>
#include "alg.h"
#include "imdb.h"
#include "cache.h"

extern pthread_mutex_t mymutex;
// Teller connecties
extern int maxconn;
extern int mconnect;
//
// //--quiet
extern int stil;
// // (default)aantal dagen om te grabben: --days
extern int days;
// // --offset
extern int offset;
// // --cache
extern short cache;
extern FILE *cachefp;
extern FILE *cachetmp;
extern short imdb;
extern short imdbdirty;
extern int aantalimdb;
extern unsigned long aantalprog;
extern unsigned long aantalcache;

//online channels voor config van tvgids halen, return 0 NOT OK.
short getchannels(void)
{
	extern channel channelsconf2[];
	CURL *handle;
	char curlerror[CURL_ERROR_SIZE];
	char buffer[1024];
	int tmpptr, tel = 0;
	char *p1, *p2;
	FILE *tempfile;
	char template[] = "/tmp/chan_XXXXXX";
	if (!(handle = curl_easy_init()))
		return (0);
	tmpptr = mkstemp(template);
	if (tmpptr == -1)
		return (0);
	tempfile = fdopen(tmpptr, "w+");
	if (tempfile == NULL)
		return (0);
	curl_easy_setopt(handle, CURLOPT_URL,
			 //"http://www.tvgids.nl/index.php");
			 "http://www.tvgids.nl/zoeken/");
	curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(handle, CURLOPT_AUTOREFERER, 1);
	curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(handle, CURLOPT_MAXREDIRS, 5);
	curl_easy_setopt(handle, CURLOPT_WRITEDATA, tempfile);
	curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, curlerror);
	curl_easy_setopt(handle, CURLOPT_TIMEOUT, TIMEOUT);
	//curl_easy_setopt(handle, CURLOPT_VERBOSE, 1);

	fprintf(stderr,
		"Ophalen zenders van tvgids.nl, momentje a.u.b.\n");
	if (curl_easy_perform(handle)) {
		fprintf(stderr, "Error online channelconfig: '%s'\n",
			curlerror);
		fclose(tempfile);
		unlink(template);
		return (0);
	}
	curl_easy_cleanup(handle);
	rewind(tempfile);
	while (fgets(buffer, 1024, tempfile)) {
		if (strstr(buffer, "<optgroup label=\"Hoofdzenders")) {
			do {
				if (strstr(buffer, "</optgroup>\r"))
					break;
				p1 = strstr(buffer, "<option");
				if (p1 == NULL)
					continue;
				p1 = strchr(p1, '"');
				p1++;
				p2 = strchr(p1, '"');
				if (p2 == NULL)
					continue;
				*p2 = '\0';
				channelsconf2[tel].id = strdup(p1);

				p2++;
				p1 = strchr(p2, '>');
				p1++;
				p2 = strchr(p1, '>');
				*p2 = '\0';
				channelsconf2[tel].omschrijving =
				    strdup(p1);
				conv_char(channelsconf2[tel].omschrijving);

				channelsconf2[tel].provider = 0;
				channelsconf2[tel].icon = NULL;
				conv_char(channelsconf2[tel].id);
				tel++;
			} while (fgets(buffer, 1024, tempfile));
		}
		if(tel >0)
			break;
	}
	if (tel > 0) {
		channelsconf2[tel].id = NULL;
		channelsconf2[tel].omschrijving = "";
	}
	fprintf(stderr, "%d zenders gevonden.\n", tel);
	fclose(tempfile);
	unlink(template);
	//fprintf(stderr,"template:'%s'\n", template);
	return (1);
}

//data ophalen / verwerken tvgids.nl
int tv_gids_nl(channel * kanaal)
{
	CURL *tvghandle;
	char curlerror[CURL_ERROR_SIZE];
	char url[2048];
	int ret, tel = 0, tel2 = 0, tel3;
	int tmpptr;
	FILE *step1fp;
	char template[21];
	char buffer[4096];
	char *buffer2;
	char *p, *p1, *p2;
	struct programma {
		char *iden;
		long pos;	//position in cache
		char dagd;	// Voor datumbepaling na 00:00 uur
		char *titel;
		char *startuur;
		char *startmin;
		char *stopuur;
		char *stopmin;
		char *cachejaar;
		char *cachemaand;
		char *cachedag;
	};
	char cjaar[5];
	char cmaand[3];
	char cdag[3];
	struct programma ids[4000];
	struct maanden {
		char maandje[4];
		char maandnr[3];
	};
	struct maanden maandjes[13] = {
		{"jan", "01"},
		{"feb", "02"},
		{"maa", "03"},
		{"apr", "04"},
		{"mei", "05"},
		{"jun", "06"},
		{"jul", "07"},
		{"aug", "08"},
		{"sep", "09"},
		{"okt", "10"},
		{"nov", "11"},
		{"dec", "12"},
		{"", ""}
	};
	char c;
	time_t timebuf;
	time_t stopvorig = 0;	//om overlappende tijden te vangen.
	time_t starthuidig = 0;	//om overlappende tijden te vangen.
	char start[50];
	char stop[50];
	char dagdeel;
	extern short tz;
	short tzone = tz, tzone2 = tz;
	char genre[50] = "";
	char *progdetail;
	short credits = 0;
	char *actors[50];
	char stars[10];
	stars[0] = '\0';
	char jaarpremiere[5];
	jaarpremiere[0] = '\0';
	char *regie[20];
	char subtitel[150];
	subtitel[0] = '\0';
	char *presentator[20];
	short videoaspect = 0;
	short subtitles = 0;
	short tocache = 0;
	char *acttmp = NULL;

	for (tel2 = 0; tel2 < 20; tel2++) {
		actors[tel2] = NULL;
		presentator[tel2] = NULL;
		regie[tel2] = NULL;
	}

	if (!(tvghandle = curl_easy_init())) {
		fprintf(stderr, "Unable to open curl easy tvghandle");
		return (3);
	}

	sprintf(template, "/tmp/%s.grab_XXXXXX", kanaal->id);
	tmpptr = mkstemp(template);
	if (tmpptr == -1)
		return (0);
	if (!(step1fp = fdopen(tmpptr, "w+"))) {
		fprintf(stderr, "ERROR openen tmpfile '%s' bij %s :",
			template, kanaal->id);
		perror("step1 site_data");
		return (0);
	}
	tel2 = offset;
	tel3 = 0;
	curl_easy_setopt(tvghandle, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(tvghandle, CURLOPT_AUTOREFERER, 1);
	curl_easy_setopt(tvghandle, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(tvghandle, CURLOPT_MAXREDIRS, 5);
	curl_easy_setopt(tvghandle, CURLOPT_WRITEDATA, step1fp);
	curl_easy_setopt(tvghandle, CURLOPT_ERRORBUFFER, curlerror);
	curl_easy_setopt(tvghandle, CURLOPT_TIMEOUT, TIMEOUT);
	//curl_easy_setopt(tvghandle, CURLOPT_VERBOSE, 1);

	while (tel3 <= MAXDAYS && tel3 < days && tel2 < 6) {
		sprintf(url,
			"http://www.tvgids.nl/zoeken/?q=&d=%d&z=%s&t=0&g=&v=0",
			tel2, kanaal->id);
		tel2++;
		tel3++;
		if (!stil)
			fprintf(stderr,
				"Ophalen \"%s\" van tvgids.nl:\n\t\"%s\"\n",
				kanaal->omschrijving, url);

		curl_easy_setopt(tvghandle, CURLOPT_URL, url);

		while (maxconn >= mconnect)
			sleep(1);
		pthread_mutex_lock(&mymutex);
		maxconn++;
		pthread_mutex_unlock(&mymutex);
		for (tel = 0; (ret = curl_easy_perform(tvghandle)); tel++) {
			if (tel == MAXRETRY - 1)
				break;
			fprintf(stderr,
				"Connect voor programma-overzicht %s van tvgids.nl: %s ; ...retrying\n",
				kanaal->omschrijving, curlerror);
		}
		if (ret) {
			fprintf(stderr,
				"\nMAXRETRY connect voor programma-overzicht %s  dag %d van tvgids.nl : %s ->mislukt\n",
				kanaal->omschrijving, tel2, curlerror);
		}
		pthread_mutex_lock(&mymutex);
		maxconn--;
		pthread_mutex_unlock(&mymutex);
		fprintf(step1fp, "\n\n");
	}
/* is misschien iets voor de toekomst....
	curly = 0;
	if(curl_easy_getinfo(tvghandle, CURLINFO_RESPONSE_CODE, &curly) == CURLE_OK )
	{
	//http response is NIET OK, stoppen
		if( curly != 200 )
		{
			fclose(step1fp);
			unlink(template);
			return(0);
		}
	}
*/
	rewind(step1fp);
	short section = 0;	//indicator voor programma-overzicht
	tel2 = 0;
	ids[tel2].iden = NULL;
	ids[tel2].titel = NULL;
	ids[tel2].startuur = NULL;
	ids[tel2].startmin = NULL;
	ids[tel2].stopuur = NULL;
	ids[tel2].stopmin = NULL;
	ids[tel2].cachejaar = NULL;
	ids[tel2].cachemaand = NULL;
	ids[tel2].cachedag = NULL;
	while (fgets(buffer, 1024, step1fp)) {
		if (buffer[0] == '')
			section = 0;
		if (strstr(buffer, "<div class=\"programs\">")) {
			section = 1;
			continue;
		}
		if (strstr(buffer, "<div class=\"program\">")) {
			section = 3;
			continue;
		}
		if (strstr(buffer, "<div class=\"clearer\">")
		    && section == 3) {
			section = 4;
		}
		//dagdeel:      
		if ((p = strstr(buffer, "<div class=\"subtitle\">")) != NULL) {
			if ((p = strchr(buffer, '>')) == NULL)
			continue;
			p++;
			dagdeel = *p;
		}
		if (!section)
			continue;

		//dagdeel:      
		if (section == 1) {
			//      !!!!! cachedatum maken !!
			if (p = strstr(buffer, "<h2>")) {
				p = strchr(buffer, '>');
				p++;
				if ((p1 = strrchr(buffer, '<')))
					*p1 = '\0';
				p1 = strtok_r(p, " ", &buffer2);
				p1 = strtok_r(NULL, " ", &buffer2);
				if (ids[tel2].cachedag != NULL) {
					free(ids[tel2].cachedag);
					ids[tel2].cachedag = NULL;
				}
				strcpy(cdag, p1);
				p1 = strtok_r(NULL, " ", &buffer2);
				if (ids[tel2].cachemaand != NULL) {
					free(ids[tel2].cachemaand);
					ids[tel2].cachemaand = NULL;
				}
				for (tel = 0; maandjes[tel].maandje[0];
				     tel++) {
					if (!strncasecmp
					    (p1, maandjes[tel].maandje, 3))
						strcpy(cmaand,
						       maandjes[tel].
						       maandnr);
				}
				p1 = strtok_r(NULL, " ", &buffer2);
				if (ids[tel2].cachejaar != NULL) {
					free(ids[tel2].cachejaar);
					ids[tel2].cachejaar = NULL;
				}
				strcpy(cjaar, p1);

			}
		}
		if (section < 3)
			continue;
		//tijden:
		if (strstr(buffer, "<span class=\"time\"") && section == 3) {
			p = strchr(buffer, '>');
			if (!p)
				continue;
			p++;
			if (isdigit(p[0]) && isdigit(p[1])
			    && isdigit(p[3]) && isdigit(p[4])) {
				ids[tel2].startuur =
				    malloc(sizeof(char) * 3);
				strncpy(ids[tel2].startuur, p, 2);
				ids[tel2].startuur[2] = '\0';
				ids[tel2].startmin =
				    malloc(sizeof(char) * 3);
				strncpy(ids[tel2].startmin, p + 3, 2);
				ids[tel2].startmin[2] = '\0';
			}
			if (isdigit(p[8]) && isdigit(p[9])
			    && isdigit(p[11]) && isdigit(p[12])) {
				ids[tel2].stopuur =
				    malloc(sizeof(char) * 3);
				strncpy(ids[tel2].stopuur, p + 8, 2);
				ids[tel2].stopuur[2] = '\0';
				ids[tel2].stopmin =
				    malloc(sizeof(char) * 3);
				strncpy(ids[tel2].stopmin, p + 11, 2);
				ids[tel2].stopmin[2] = '\0';
			}
		}
		//Programmurl
		if ((p1 = strstr(buffer, "<a href=\"/programma/"))
		    && section == 3) {
			if ((p = strchr(p1, '"')) == NULL)
				continue;
			p++;
			p1 = strrchr(p, '"');
			*p1 = '\0';
			ids[tel2].iden =
			    malloc((strlen(p) + 1) * sizeof(char));
			strcpy(ids[tel2].iden, p);
		}
		//titel
		if ((p1 = strstr(buffer, "<span class=\"title\""))
		    && section == 3) {
			if ((p = strchr(p1, '>')) == NULL)
				continue;
			p++;
			p1 = strchr(p, '<');
			*p1 = '\0';
			ids[tel2].titel =
			    malloc((strlen(p) + 50) * sizeof(char));
			strcpy(ids[tel2].titel, p);
			conv_char(ids[tel2].titel);
			ids[tel2].cachejaar = strdup(cjaar);
			ids[tel2].cachemaand = strdup(cmaand);
			ids[tel2].cachedag = strdup(cdag);
		}
		if (section == 4) {
			section = 0;
			ids[tel2].dagd = dagdeel;
			// programma zonder starttijd niet opnemen in array:
			if (!ids[tel2].startuur) {
				if (ids[tel2].iden != NULL) {
					free(ids[tel2].iden);
					ids[tel2].iden = NULL;
				}
				if (ids[tel2].titel != NULL) {
					free(ids[tel2].titel);
					ids[tel2].titel = NULL;
				}
				if (ids[tel2].startuur != NULL) {
					free(ids[tel2].startuur);
					ids[tel2].startuur = NULL;
				}
				if (ids[tel2].startmin != NULL) {
					free(ids[tel2].startmin);
					ids[tel2].startmin = NULL;
				}
				if (ids[tel2].stopuur != NULL) {
					free(ids[tel2].stopuur);
					ids[tel2].stopuur = NULL;
				}
				if (ids[tel2].stopmin != NULL) {
					free(ids[tel2].stopmin);
					ids[tel2].stopmin = NULL;
				}
				continue;
			}

			tel2++;
			ids[tel2].iden = NULL;
			ids[tel2].titel = NULL;
			ids[tel2].startuur = NULL;
			ids[tel2].startmin = NULL;
			ids[tel2].stopuur = NULL;
			ids[tel2].stopmin = NULL;
			ids[tel2].cachejaar = NULL;
			ids[tel2].cachemaand = NULL;
			ids[tel2].cachedag = NULL;
		}
	}

	for (tel = 0; ids[tel].iden; tel++) {
		if (cache) {	//als in cache niet online gaan
			ids[tel].pos = vind_cache(ids[tel].iden, '0');
			if (ids[tel].pos != -1) {
				printcache(ids[tel].pos);
				pthread_mutex_lock(&mymutex);
				aantalcache++;
				pthread_mutex_unlock(&mymutex);
				continue;
			}
		}

		sprintf(url, "http://www.tvgids.nl%s", ids[tel].iden);

		while (maxconn >= mconnect)
			sleep(1);
		pthread_mutex_lock(&mymutex);
		maxconn++;
		pthread_mutex_unlock(&mymutex);
		rewind(step1fp);
		truncate(template, 0);
		curl_easy_setopt(tvghandle, CURLOPT_URL, url);
		ret = curl_easy_perform(tvghandle);
		for (tel2 = 0; ret; tel2++) {
			if (tel2 == MAXRETRY - 1)
				break;
			fprintf(stderr,
				"\nconnect %s voor programma-id %s: %s ; ...retrying\n",
				kanaal->omschrijving, ids[tel].iden,
				curlerror);
			rewind(step1fp);
			truncate(template, 0);
			ret = curl_easy_perform(tvghandle);
		}
		if (ret) {
			fprintf(stderr,
				"\nMAXRETRY connect %s %s: %s ->mislukt\n",
				kanaal->omschrijving, ids[tel].iden,
				curlerror);
			truncate(template, 0);
		}

		pthread_mutex_lock(&mymutex);
		maxconn--;
		pthread_mutex_unlock(&mymutex);
		rewind(step1fp);

		section = 0;
		while (fgets(buffer, 1024, step1fp)) {
			if (strstr(buffer, "<div id=\"content-col-left\">")) {
				section = 1;
				continue;
			}
			if (section != 1)
				continue;

			// Details programma:
			if (strstr(buffer, "<div id=\"prog-content\">")) {
				fgets(buffer, 1024, step1fp);
				// Genre:
				if (p = strstr(buffer, "<strong>")) {
					p += 8;
					if(*p != '<') {
						strcpy(genre, p);
						if(p = strrchr(genre, '<') )
							*p = '\0';
					}
				}

				progdetail = calloc(sizeof(char), 4096);
				short readincomplete = 0;
				//Evt. Type meenemen in omschrijving
/*
				if (p = strchr(buffer, '>')) {
					p++;
					//tags overslaan:
					while (*p == '<') {
						if (p = strchr(p, '>'))
							p++;
					}
				}
*/

				if (p = strchr(buffer, '>')) {
					p++;
					if (p1 = strchr(p, '<')) {
						p1[1] = '\0';
						*p1 = ' ';
					}

					if (strlen(p) == 1 && p[0] == '\n')
						progdetail[0] = '\0';
					if (strlen(p) > 0) {
						strcpy(progdetail, p);
					}
				} else
					progdetail[0] = '\0';

				fgets(buffer, 1024, step1fp);
				tel3 = 0;
				do {
					if (strstr(buffer, "<div id=\"prog-nextprev\">"))
						break;
					// Als we niet de alles van 1 regel in de buffer hadden:
					if (readincomplete) {
						if ((p1 =
						     strchr(buffer,
							    '<'))) {
							readincomplete = 0;
							if (!strncmp
							    (p1, "</p>",
							     4)) {
								*p1 = '\n';
								p1++;
							}
							*p1 = '\0';
							if(strlen(progdetail)+strlen(buffer) > 4096)
								continue;
							if (strlen(buffer)
							    > 0)
								strcat
								    (progdetail,
								     buffer);
						} else {
							if(strlen(progdetail)+strlen(buffer) > 4096)
								continue;
							if (strlen(buffer)
							    > 0)
								strcat
								    (progdetail,
								     buffer);
						}
						continue;
					}
					if ((p = strchr(buffer, '>'))) {
						p++;
						// Lege paragraaf , overslaan:
						if (!strncmp(p, "</p", 3))
							continue;
						//tags overslaan:
						if (!strncmp(p, "<li>", 4))
							p += 4;
						if ((p1 = strrchr(p, '<'))) {
							if (!strncmp
							    (p1, "</p>",
							     4)) {
								*p1 = '\n';
								p1++;
							}
							*p1 = '\0';
							readincomplete = 0;
						} else
							readincomplete = 1;
						if (strlen(p) > 0) {
							//Als Uppercase typeaanduiding NIET meenemen.
/*
							if (!tel3
							    &&
							    !islower(*p))
								progdetail
								    [0] =
								    '\0';
*/
							strcat(progdetail,
							       p);
							tel3++;
						}

					}
					if (strstr(buffer, "</div>"))
						break;
				} while (fgets(buffer, 1024, step1fp));

				while (tel3 = strlen(progdetail) - 1) {
					if (progdetail[tel3] == '\r' ||
					    progdetail[tel3] == '\n')
						progdetail[tel3] = '\0';
					else
						break;
				}
			}
			// Einde Detailomschrijving programma:
			//Genre, als niet al uit type bij progdetail:
			if ((p2=strstr(buffer, "<li><strong>Genre:")) && strlen(genre) == 0) {
				if( p = strstr(p2, "</strong>") ) {
					p1 = ++p;
					if( p = strchr(p1, '<'))
						*p = '\0';	
					if( p = strchr(p1, '>') )
						p++;
				}
				if( strlen(p) > 0) {
					strcpy(genre, p);
				}
					
				continue;
			}
			//Acteurs:
			if (p2=strstr(buffer, "<li><strong>Acteurs:")) {
				if( p = strstr(p2, "</strong>") ) {
					p1 = ++p;
					if( p = strchr(p1, '<'))
						*p = '\0';	
					if( p = strchr(p1, '>') )
						p++;
				}
				if( strlen(p) > 0) {
					maak_presenters(p,
							actors);
					credits = 1;
				}
			}
			//Regie:
			if (p2=strstr(buffer, "<li><strong>Regisseur:")) {
				if( p = strstr(p2, "</strong>") ) {
					p1 = ++p;
					if( p = strchr(p1, '<'))
						*p = '\0';	
					if( p = strchr(p1, '>') )
						p++;
				}
				if( strlen(p) > 0) {
					maak_presenters(p, regie);
					credits = 1;
				}
			}
			//Jaar van premiere:
			if (p2=strstr(buffer, "<li><strong>Jaar van premiere:")) {
				if( p = strstr(p2, "</strong>") ) {
					p1 = ++p;
					if( p = strchr(p1, '<'))
						*p = '\0';	
					if( p = strchr(p1, '>') )
						p++;
				}
				if( strlen(p) > 0) {
					strcpy(jaarpremiere,p);
				}
			}
			//Bijzonderheden:
			if (strstr(buffer, "<li><strong>Bijzonderheden:")) {
				if (strcasestr(buffer, "breedbeeld"))
					videoaspect = 1;
				if (strcasestr(buffer, "Teletekst ondertiteld"))
					subtitles = 1;
			}
			//Presentatie:
			if (p2=strstr(buffer, "<li><strong>Presentatie:")) {
				if( p = strstr(p2, "</strong>") ) {
					p1 = ++p;
					if( p = strchr(p1, '<'))
						*p = '\0';	
					if( p = strchr(p1, '>') )
						p++;
				}
				if( strlen(p) > 0) {
					maak_presenters(p, presentator);
					credits = 1;
				}
			}
			//Einde detailpagina:
			if (strstr(buffer, "<div id=\"prog-info-footer\">")) {
				section = 0;
				if (ids[tel].startuur) {
					// als start en stop gelijk , entry negeren:
					if (ids[tel].stopuur
					    && ids[tel].stopmin) {
						if (!strcmp
						    (ids[tel].startuur,
						     ids[tel].stopuur)
						    && !strcmp(ids[tel].
							       startmin,
							       ids[tel].
							       stopmin))
							break;
					}
					pthread_mutex_lock(&mymutex);
					timebuf =
					    makedate(atoi
						     (ids[tel].cachejaar),
						     atoi(ids[tel].
							  cachemaand),
						     atoi(ids[tel].
							  cachedag),
						     atoi(ids[tel].
							  startuur),
						     atoi(ids[tel].
							  startmin), start,
						     tzone, -1);
					if (ids[tel].dagd == 'A'
					    || ids[tel].dagd == 'N') {
						if (atoi(ids[tel].startuur)
						    < 10)
							starthuidig =
							    makedate(0, 0,
								     0, 0,
								     0,
								     start,
								     tzone,
								     timebuf
								     +
								     (3600
								      *
								      24));
						else
							starthuidig =
							    makedate(0, 0,
								     0, 0,
								     0,
								     start,
								     tzone,
								     timebuf);
					} else
						starthuidig =
						    makedate(0, 0, 0, 0, 0,
							     start, tzone,
							     timebuf);
					//overlappende tijden proberen te vangen:
					//als de vorige stoptijd over de starttijd heengaat,
					//starttijd aanpassen, is gokje, maar je moet iets...
					if (tel && stopvorig) {
						if (stopvorig >
						    starthuidig) {
							makedate(0, 0, 0,
								 0, 0,
								 start,
								 tzone,
								 stopvorig);
						}
					}
					stopvorig = 0;

					//rekening houden met missing eindtijd:
					//NIET Cachen als geen eindtijd.
					if (ids[tel].stopuur) {
						timebuf =
						    makedate(atoi
							     (ids[tel].
							      cachejaar),
							     atoi(ids[tel].
								  cachemaand),
							     atoi(ids[tel].
								  cachedag),
							     atoi(ids[tel].
								  stopuur),
							     atoi(ids[tel].
								  stopmin),
							     stop, tzone,
							     -1);
						if (ids[tel].dagd == 'A'
						    || ids[tel].dagd ==
						    'N') {
							if (atoi
							    (ids[tel].
							     stopuur) < 10)
								stopvorig =
								    makedate
								    (0, 0,
								     0, 0,
								     0,
								     stop,
								     tzone2,
								     timebuf
								     +
								     (3600
								      *
								      24));
							else
								stopvorig =
								    makedate
								    (0, 0,
								     0, 0,
								     0,
								     stop,
								     tzone2,
								     timebuf);
						} else
							stopvorig =
							    makedate(0, 0,
								     0, 0,
								     0,
								     stop,
								     tzone2,
								     timebuf);
						printf
						    (" <programme start=\"%s +0%d00\" stop=\"%s +0%d00\" channel=\"%s.tvgids.nl\">\n",
						     start, tzone, stop,
						     tzone2, kanaal->id);
						if (cache) {
							tocache = 1;
							fseek(cachetmp, 0,
							      SEEK_END);
							fprintf(cachetmp,
								"0%s-%s%s%s",
								ids[tel].
								iden,
								ids[tel].
								cachejaar,
								ids[tel].
								cachemaand,
								ids[tel].
								cachedag);
							fprintf(cachetmp,
								" <programme start=\"%s +0%d00\" stop=\"%s +0%d00\" channel=\"%s.tvgids.nl\">\n",
								start,
								tzone,
								stop,
								tzone2,
								kanaal->
								id);
						}
					} else {
						printf
						    (" <programme start=\"%s +0%d00\" channel=\"%s.tvgids.nl\">\n",
						     start, tzone,
						     kanaal->id);
					}
					convert_genre(genre);
					splits_titel(ids[tel].titel, subtitel, genre);
					printf
					    ("   <title lang=\"nl\">%s</title>\n",
					     ids[tel].titel);
					if (tocache)
						fprintf(cachetmp,
							"   <title lang=\"nl\">%s</title>\n",
							ids[tel].titel);
					if (subtitel[0] != '\0') {
						fprintf(stdout,
							"   <sub-title lang=\"nl\">%s</sub-title>\n",
							subtitel);
						if (tocache)
							fprintf(cachetmp,
								"   <sub-title lang=\"nl\">%s</sub-title>\n",
								subtitel);
					}
					if (progdetail != NULL
					    && progdetail[0] != '\0') {
						conv_char(progdetail);
						printf
						    ("   <desc lang=\"nl\">%s\n",
						     progdetail);
						if (tocache)
							fprintf(cachetmp,
								"   <desc lang=\"nl\">%s\n",
								progdetail);
						if (jaarpremiere[0] !=
						    '\0') {
							printf
							    ("Jaar: %s\n",
							     jaarpremiere);
							if (tocache)
								fprintf
								    (cachetmp,
								     "Jaar: %s\n",
								     jaarpremiere);
						}
						printf("   </desc>\n");
						if (tocache)
							fprintf(cachetmp,
								"   </desc>\n");
					}
					if (credits) {
						fprintf(stdout,
							"   <credits>\n");
						if (tocache)
							fprintf(cachetmp,
								"   <credits>\n");
						for (tel2 = 0;
						     actors[tel2] != NULL;
						     tel2++) {
							fprintf(stdout,
								"       <actor>%s</actor>\n",
								actors
								[tel2]);
							if (tocache)
								fprintf
								    (cachetmp,
								     "       <actor>%s</actor>\n",
								     actors
								     [tel2]);
						}
						for (tel2 = 0;
						     regie[tel2] != NULL;
						     tel2++) {
							fprintf(stdout,
								"       <director>%s</director>\n",
								regie
								[tel2]);
							if (tocache)
								fprintf
								    (cachetmp,
								     "       <director>%s</director>\n",
								     regie
								     [tel2]);
						}
						for (tel2 = 0;
						     presentator[tel2] !=
						     NULL; tel2++) {
							fprintf(stdout,
								"       <presenter>%s</presenter>\n",
								presentator
								[tel2]);
							if (tocache)
								fprintf
								    (cachetmp,
								     "       <presenter>%s</presenter>\n",
								     presentator
								     [tel2]);
						}
						fprintf(stdout,
							"   </credits>\n");
						if (tocache)
							fprintf(cachetmp,
								"   </credits>\n");
					}
					if (jaarpremiere[0] != '\0') {
						fprintf(stdout,
							"   <date>%s</date>\n",
							jaarpremiere);
						if (tocache)
							fprintf(cachetmp,
								"   <date>%s</date>\n",
								jaarpremiere);
					}
					//category Movies uit omschrijving :
					printf
					    ("   <category>%s</category>\n",
					     genre);
					if (tocache)
						fprintf(cachetmp,
							"   <category>%s</category>\n",
							genre);
					if (imdb) {
						//wachten op usable imdb
						while (imdbdirty && imdb)
							sleep(3);
						if (imdb) {
							tel2 =
							    get_rating(ids
								       [tel].
								       titel,
								       stars,
								       jaarpremiere,
								       NULL,
								       genre);
							if (tel2 <= 0)
								stars[0] =
								    '\0';
							else
								aantalimdb++;
						}
					}
					if (stars[0] != '\0') {
						printf
						    ("   <star-rating>\n    <value>%s/10</value>\n   </star-rating>\n",
						     stars);
						if (tocache)
							fprintf(cachetmp,
								"   <star-rating>\n    <value>%s/10</value>\n   </star-rating>\n",
								stars);
					}
					if (videoaspect) {
						printf
						    ("   <video>\n      <aspect>16:9</aspect>\n   </video>\n");
						if (tocache)
							fprintf(cachetmp,
								"   <video>\n      <aspect>16:9</aspect>\n   </video>\n");
					}
					if (subtitles) {
						printf
						    ("   <subtitles type=\"teletext\" />\n");
						if (tocache)
							fprintf(cachetmp,
						    		"   <subtitles type=\"teletext\" />\n");
					}
					printf(" </programme>\n");
					if (tocache) {
						fprintf(cachetmp,
							" </programme>\n");
						fprintf(cachetmp, "\n");
					}
					aantalprog++;
					fflush(NULL);
					pthread_mutex_unlock(&mymutex);
				}
				//resetten voor volgende programma-id:
				credits = 0;
				videoaspect = 0;
				subtitles = 0;
				if (progdetail != NULL) {
					free(progdetail);
					progdetail = NULL;
				}
				for (tel2 = 0; actors[tel2] != NULL;
				     tel2++) {
					free(actors[tel2]);
					actors[tel2] = NULL;
				}
				for (tel2 = 0; regie[tel2] != NULL; tel2++) {
					free(regie[tel2]);
					regie[tel2] = NULL;
				}
				for (tel2 = 0; presentator[tel2] != NULL;
				     tel2++) {
					free(presentator[tel2]);
					presentator[tel2] = NULL;
				}

				subtitel[0] = '\0';
				genre[0] = '\0';
				jaarpremiere[0] = '\0';
				stars[0] = '\0';
				if (ids[tel].iden != NULL);
				free(ids[tel].iden);
				if (ids[tel].titel != NULL);
				free(ids[tel].titel);
				tocache = 0;
				break;
			}
		}
	}
	curl_easy_cleanup(tvghandle);

	//fprintf(stderr, "template %s\n", template);
	fclose(step1fp);
	unlink(template);

	return (ret);
}
